package handler

import (
	"com-mgmt/cache"
	"com-mgmt/model"
	"com-mgmt/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	data := model.User{
		Username: username,
		Password: password,
	}
	redis_login_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errCount > 5 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "同 IP 连续失败>5 次，5 分钟内拒绝",
		})
		return
	}

	err := model.DB.Where("username=?", username).First(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账号或密码错误",
		})
		return
	}
	if data.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if data.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误三次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": data,
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	var data []model.Role

	/*SELECT
	  *
	FROM
	  roles
	  LEFT JOIN user_roles ON user_roles.rid = roles.id
	WHERE
	  user_roles.uid =1*/

	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid =?", uid).
		Debug().Find(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	var data []model.Node

	/*SELECT
	  *
	FROM
	  nodes
	  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
	WHERE
	  role_nodes.rid = 1*/

	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid =?", rid).
		Debug().Find(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return
}
